package com.demo.hdz.myfileexplorer.fileexplorer;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.demo.hdz.myfileexplorer.Logger;
import com.demo.hdz.myfileexplorer.MainActivity;
import com.demo.hdz.myfileexplorer.R;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author hdz
 * @date 2018/11/24 13:12
 */
public class FileSelectActivity extends ListActivity {

    private List<String> mItems = null;
    private List<String> mPaths = null;
    private String mRootPath = "/";
    private String mCurrPath = "";
    private TextView mTvPath;
    private static final String TAG = "FileSelectActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_file_select);

        mCurrPath = getLatestPath(this, mCurrPath);
        Logger.d(TAG+",onCreate: mCurrPath = " + mCurrPath);

        mTvPath = (TextView) findViewById(R.id.currPathText);

        ImageView imgFolderUp = (ImageView) findViewById(R.id.imgFolderUp);
        imgFolderUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                folderUp();
            }
        });

        Button btnConfirm = (Button) findViewById(R.id.confirmBtn);
        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                returnFilePath();
            }
        });

        Button btnCancel = (Button) findViewById(R.id.cancelBtn);
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        if ("".equals(mCurrPath)) {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                File sdCardDir = Environment.getExternalStorageDirectory();
                getFileDir(sdCardDir.getPath());
            } else {
                getFileDir(mRootPath);
            }
        } else {
            getFileDir(mCurrPath);
        }
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        String path = mPaths.get(position);
        Logger.d(TAG+",onListItemClick: path = " + path);
        File file = new File(path);
        if (file.isDirectory()) {
            mCurrPath = mPaths.get(position);
            if (mCurrPath != null) {
                setLatestPath(this, mCurrPath);
                getFileDir(mPaths.get(position));
            }
        } else {
            mCurrPath = mPaths.get(position);
            returnFilePath();
        }
    }

    private void returnFilePath() {
        Intent intent = new Intent(FileSelectActivity.this, MainActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("file", mCurrPath);
        intent.putExtras(bundle);
        setResult(Activity.RESULT_OK, intent);
        finish();
    }


    private void getFileDir(String sFilePath) {
        String currPath = sFilePath;
        mTvPath.setText("当前路径："+currPath);
        if (mItems == null) {
            mItems = new ArrayList<String>();
        } else {
            mItems.clear();
        }
        if (mPaths == null) {
            mPaths = new ArrayList<String>();
        } else {
            mPaths.clear();
        }

        File file = new File(currPath);
        File[] fileList = file.listFiles();
        if (fileList == null) {
            currPath = file.getParent();
            mTvPath.setText("当前路径："+currPath);
            file = new File(currPath);
            fileList = file.listFiles();
            setLatestPath(this, currPath);
        }
        Logger.d(TAG+",getFileDir: length = " + fileList.length);
        int pos = 0;

        //按文件名排序
        List files2 = Arrays.asList(fileList);
        Collections.sort(files2, new Comparator<File>() {
            @Override
            public int compare(File o, File t1) {
                if (o.isDirectory() && t1.isFile()) {
                    return -1;
                }
                if (o.isFile() && t1.isDirectory()) {
                    return 1;
                }
                return o.getName().compareToIgnoreCase(t1.getName());
            }
        });
        Logger.d(TAG+",getFileDir: files2.size() = " + files2.size() + ", mPaths.size() = " + mPaths.size());
        for (int i=0; i<files2.size(); i++) {
            File f = (File)files2.get(i);
            if (!f.getName().startsWith(".")) {
                if (f.isDirectory()) {
                    mItems.add(pos, f.getName());
                    mPaths.add(pos, f.getPath());
                    pos++;
                } else {
                    mItems.add(f.getName());
                    mPaths.add(f.getPath());
                }
                Logger.d(TAG+",getFileDir: " + f.getPath());
            }
        }

        Logger.d(TAG+",getFileDir: mPaths.get(0) = " + mPaths.get(0) + ", mPaths.size() = " + mPaths.size());
        setListAdapter(new FileInfosAdapter(this, mItems, mPaths));
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        finish();
        //禁用触摸
        return false;
    }


    public static void setLatestPath(Context context, String path) {
        SharedPreferences preferences = context.getSharedPreferences("config", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("LatestPath", path);
        editor.commit();
    }

    public static String getLatestPath(Context context, String def) {
        if (context == null) {
            return "";
        }
        SharedPreferences preferences = context.getSharedPreferences("config", Context.MODE_PRIVATE);
        return preferences.getString("LatestPath", def);
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    private void folderUp() {
        Logger.d(TAG+",folderUp: mCurrPath=" + mCurrPath);
        File file = new File(mCurrPath);
        mCurrPath = file.getParent();
        setLatestPath(this, mCurrPath);
        getFileDir(mCurrPath);
    }
}
